package com.heima.app.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //0.获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        //1、判断是否为登录请求
        if (path.contains("/login")){
            //1.1 是  放行
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        //1.2 否   是否有token
        if (StringUtils.isBlank(token)){
            //无token  登录失败，返回错误码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //有 校验token
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //验证是否有限期内  -1：有效，0：有效，1：过期，2：过期
            int result = AppJwtUtil.verifyToken(claims);
            //token在有效期内
            if (result==-1||result==0){
                if (claims!=null){
                    //从token中获取useId
                    Object userId =claims.get("id");
                    //将数据设置到请求头
                    ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders ->
                            httpHeaders.add("userId", userId+"")).build();
                    //重置请求头
                    exchange.mutate().request(serverHttpRequest).build();
                }
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //token解析失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //token 过期了
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
